package vn.easyticket.db;

import org.springframework.context.support.GenericXmlApplicationContext;

import vn.easyticket.db.exceptions.NoServiceFoundException;
import vn.easyticket.db.facet.AbstractReposityService;

public class RepositoriesServiceFactoryImpl
    implements RepositoriesServiceFactory
{
    private final String APP_CONTEXT_FILE_PATH = "classpath:spring-data-app-context.xml";

    private static RepositoriesServiceFactoryImpl singletonInstance = null;

    private GenericXmlApplicationContext context = null;

    private RepositoriesServiceFactoryImpl()
    {
        this.context = new GenericXmlApplicationContext();
        context.load( APP_CONTEXT_FILE_PATH );
        context.refresh();
    }

    public static RepositoriesServiceFactoryImpl getInstance()
    {
        if ( singletonInstance == null )
        {
            synchronized ( RepositoriesServiceFactoryImpl.class )
            {
                if ( singletonInstance == null )
                {
                    singletonInstance = new RepositoriesServiceFactoryImpl();
                }
            }
        }
        return singletonInstance;
    }

    public <T extends AbstractReposityService<?, ?>> T getService( Class<T> serviceType )
        throws NoServiceFoundException
    {
        try
        {
            T service = null;
            String serviceName = ServiceNameUtil.getServiceName( serviceType );
            service = context.getBean( serviceName, serviceType );
            return service;
        }
        catch ( Exception ex )
        {
            throw new NoServiceFoundException();
        }

    }

}
